//
//  JoinViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/2/26.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

protocol JoinVcDelegate {
    func joinViewController_closeWindow()
}


class JoinViewController: NSViewController {
    
    var option:OptionData!
    var delegate:JoinVcDelegate?
    
    var currentWindow:NSWindow? {
        return self.view.window
    }
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kJoinWinWidth, kJoinWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    convenience init(option:OptionData?) {
        self.init()
        self.option = option
        self.setupUI()
        self.loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        self.setCustomWin()
        //登录状态
        NotificationCenter.default.addObserver(self, selector: #selector(loginStatus(notification:)), name: MTLoginStateNotification, object: nil)
        
        //需要进入会议
        NotificationCenter.default.addObserver(self, selector: #selector(doMeetingNot(not:)), name: MTDoMeetingNotification, object: nil)
    }
    
    func setCustomWin() {
        self.currentWindow?.collectionBehavior = NSWindow.CollectionBehavior.fullScreenPrimary
        
        self.currentWindow?.styleMask = [.titled,.fullSizeContentView]
        self.currentWindow?.isOpaque = true
        
        //设置圆角
        self.currentWindow?.contentView?.wantsLayer = true
        self.currentWindow?.contentView?.layer?.masksToBounds = true
        self.currentWindow?.contentView?.layer?.cornerRadius = 5
        self.currentWindow?.backgroundColor = NSColor.clear
        
        //可拖动的
        self.currentWindow?.isMovable = false
        self.currentWindow?.isMovableByWindowBackground = false
        
        //隐藏
        self.currentWindow?.titlebarAppearsTransparent = true
        self.currentWindow?.titleVisibility = .hidden
        self.currentWindow?.toolbar?.showsBaselineSeparator = false
        
        self.currentWindow?.standardWindowButton(.closeButton)?.isHidden = true
        self.currentWindow?.standardWindowButton(.zoomButton)?.isHidden = true
        self.currentWindow?.standardWindowButton(.miniaturizeButton)?.isHidden = true
    }
    
    func setInitialFrame(rect:NSRect) {
        self.currentWindow?.setFrameOrigin(rect.origin)
        self.currentWindow?.setContentSize(rect.size)
    }
    
    @objc func closeWindow() {
        if let degate = self.delegate {
            degate.joinViewController_closeWindow()
        }
    }
    
    func loadData() {
        self.meetingField.textField.stringValue = self.option!.roomid ?? "000 000"
        self.meetingField.textField.isEnabled = self.option!.isjoin
        
        if self.option.name != nil {
            self.nameField.textField.stringValue = self.option.name ?? "壹会通"
        }
        
        
        let video = Td.sh().lc.isVdOpen ? NSButton.StateValue.off:NSButton.StateValue.on
        self.videoBtn.state = video
        
        let audio = Td.sh().lc.isMute ? NSButton.StateValue.on:NSButton.StateValue.off
        self.audioBtn.state = audio
        
        if let string = PLISTSaveManager.readList()[safe: 0] {
            let mode = Plist_historyMode.deserialize(from: string.toDict())
            self.meetingField.textField.stringValue = mode?.roomId ?? ""
        }
    }
    
    
    lazy var closeWindowBtn: ZHButton = {
        let btn = ZHButton.init()
        btn.normalImage = NSImage.image(name:"btn_close_pressed")!
        btn.target = self
        btn.action = #selector(closeWindow)
        btn.isHidden = true
        return btn
    }()
    
    func setupUI() {
        self.view.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(NSEdgeInsetsMake(40, 30, 20, 30))
        }
        
        self.view.addSubview(closeWindowBtn)
        closeWindowBtn.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.top.equalTo(20)
            make.width.height.equalTo(12)
        }
        
        //会议号
        self.contentView.addSubview(meetingLab)
        meetingLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.top.width.centerX.equalToSuperview()
        }
        
        self.contentView.addSubview(meetingField)
        meetingField.snp.makeConstraints { (make) in
            make.height.equalTo(50)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(meetingLab.snp.bottom).offset(-15)
        }
        
        self.meetingField.addSubview(historyBtn)
        historyBtn.snp.makeConstraints { (make) in
            make.width.equalTo(24)
            make.height.equalTo(24)
            make.centerY.equalToSuperview().offset(5)
            make.right.equalTo(-5)
        }
        
        
        //您的姓名
        self.contentView.addSubview(nameLab)
        nameLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(80)
        }
        
        self.contentView.addSubview(nameField)
        nameField.snp.makeConstraints { (make) in
            make.height.equalTo(50)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(nameLab.snp.bottom).offset(-40)
        }
        
        self.contentView.addSubview(tipLab)
        tipLab.snp.makeConstraints { (make) in
            make.width.centerX.equalToSuperview()
            make.height.equalTo(18)
            make.top.equalTo(nameField.snp.bottom).offset(5)
        }
        
        //会议设置
        self.contentView.addSubview(setLab)
        setLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.width.centerX.equalToSuperview()
            make.top.equalTo(160)
        }
        
        self.contentView.addSubview(videoBtn)
        videoBtn.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.top.equalTo(setLab.snp.bottom).offset(-40)
            make.width.equalTo(200)
            make.left.equalToSuperview()
        }
        self.contentView.addSubview(audioBtn)
        audioBtn.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.top.equalTo(videoBtn.snp.bottom).offset(15)
            make.width.equalTo(200)
            make.left.equalToSuperview()
        }
        
        //加入按钮
        self.contentView.addSubview(joinBtn)
        joinBtn.snp.makeConstraints { (make) in
            make.height.equalTo(32)
            make.width.equalTo(80)
            make.bottom.equalTo(-10)
            make.right.equalTo(0)
        }
        
        self.contentView.addSubview(cacalBtn)
        cacalBtn.snp.makeConstraints { (make) in
            make.height.equalTo(32)
            make.width.equalTo(60)
            make.bottom.equalTo(-10)
            make.right.equalTo(joinBtn.snp.left).offset(-10)
        }
    }
    
    lazy var contentView: NSView = {
        let view = NSView.init()
        return view
    }()
    
    lazy var meetingBg: NSView = {
        let view = NSView.init()
        return view
    }()
    
    lazy var meetingField: ZHTextField = {
        let view = ZHTextField.init()
        let string = NSAttributedString.init(string: "输入会议ID".localized(), attributes: [
            NSAttributedString.Key.foregroundColor:color_gray(120),
            NSAttributedString.Key.font:NSFont.init(name: "Hiragino Sans CNS", size: 16) ?? NSFont.systemFont(ofSize: 16)
        ])
        view.title = "会议ID"
        view.placeholderAttributedString = string
        view.style = .number
        view.boardWidth = 1
        view.textField.delegate = self
        view.radius = 6
        view.textField.becomeFirstResponder()
        view.isBecomeFirst = true
        return view
    }()
    
    lazy var nameField: ZHTextField = {
        let view = ZHTextField.init()
        let string = NSAttributedString.init(string: "输入您的名字".localized(), attributes: [
            NSAttributedString.Key.foregroundColor:color_gray(120),
            NSAttributedString.Key.font:NSFont.init(name: "Hiragino Sans CNS", size: 16) ?? NSFont.systemFont(ofSize: 16)
        ])
        view.title = "您的名字"
        view.placeholderAttributedString = string
        view.boardWidth = 1
        view.textField.delegate = self
        view.radius = 6
        return view
    }()
    
    lazy var historyBtn: ZHButton = {
        let btn =  ZHButton.init()
        btn.normalImage =  NSImage.image(name:"icon_join_history")!
        btn.backgroundNormalColor = NSColor.clear
        btn.backgroundSelectedColor = NSColor.clear
        btn.backgroundHoverColor = color_gray(240)
        btn.backgroundHighlightColor = color_gray(240)
        btn.hasBorder = true
        btn.zh_cornerRadius = 12
        btn.target = self
        btn.action = #selector(historyBtnAction(senber:))
        return btn
    }()
    
    lazy var videoBtn: NSButton = {
        let btn = NSButton.init(frame: NSRect.zero)
        btn.setButtonType(NSButton.ButtonType.switch)
        btn.title = "保持摄像头关闭".localized()
        btn.font = NSFont.systemFont(ofSize: 14)
        btn.target = self
        btn.action = #selector(videoBtnAction(senber:))
        return btn
    }()
    
    lazy var audioBtn: NSButton = {
        let btn = NSButton.init(frame: NSRect.zero)
        btn.setButtonType(NSButton.ButtonType.switch)
        btn.title = "不自动连接音频".localized()
        btn.state = NSButton.StateValue.on
        btn.font = NSFont.systemFont(ofSize: 14)
        btn.target = self
        btn.action = #selector(audioBtnAction(senber:))
        return btn
    }()
    
    lazy var cacalBtn: ZHButton = {
        let btn = ZHButton()
        btn.zh_font = NSFont.systemFont(ofSize: 14)
        btn.zh_title = "取消".localized()
        btn.normalColor = color_gray(0)
        btn.selectedColor = color_gray(0)
        btn.hoverColor = NSColor.white
        btn.highlightColor = NSColor.white
        btn.backgroundNormalColor = color_gray(230)
        btn.backgroundSelectedColor = color_gray(230)
        btn.backgroundHoverColor = color_main108
        btn.backgroundHighlightColor = color_main108
        btn.hasBorder = true
        btn.zh_cornerRadius = 10
        btn.target = self
        btn.action = #selector(cacalBtnAction(senber:))
        return btn
    }()
    
    lazy var joinBtn: ZHButton = {
        let btn = ZHButton()
        btn.zh_font = NSFont.systemFont(ofSize: 14)
        btn.zh_title = "进入会议".localized()
        btn.normalColor = NSColor.white
        btn.selectedColor = NSColor.white
        btn.hoverColor = NSColor.white
        btn.highlightColor = NSColor.white
        btn.backgroundNormalColor = color_main108
        btn.backgroundSelectedColor = color_main108
        btn.backgroundHoverColor = color_main108.withAlphaComponent(0.8)
        btn.backgroundHighlightColor = color_main108.withAlphaComponent(0.8)
        btn.zh_cornerRadius = 10
        btn.hasBorder = true
        btn.zh_borderWidth = 1
        btn.keyEquivalent = "\r"
        btn.target = self
        btn.action = #selector(joinBtnAction(senber:))
        return btn
    }()
    
    lazy var meetingLab: NSLabel = {
        let tef = NSLabel.label(title: "会议号".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 12))
        tef.isHidden = true
        return tef
    }()
    
    lazy var nameLab: NSLabel = {
        let tef = NSLabel.label(title: "您的姓名".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 12))
        tef.isHidden = true
        return tef
    }()
    
    lazy var tipLab: NSLabel = {
        let tef = NSLabel.label(title: "(仅支持汉字，字母，数字，16字符以内)".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 10))
        return tef
    }()
    
    
    lazy var setLab: NSLabel = {
        let tef = NSLabel.label(title: "会议设置".localized(), textColor: color_gray(160), font: NSFont.systemFont(ofSize: 12))
        tef.isHidden = true
        return tef
    }()
    
    
    @objc func cacalBtnAction(senber:ZHButton) {
        self.closeWindow()
    }
    
    @objc func joinBtnAction(senber:ZHButton) {
        let txt = self.nameField.textField.stringValue
        if txt == "" {
            show_msg("请输入有效的名称".localized())
            return
        }else if String.validatedNickName(nickNameStr: txt) != true {
            self.tipLab.textColor = NSColor.red
            return
        }
        
        if txt != Td.sh().lc.nickName {
            Td.sh().lc.nickName = txt
            UserInfoManager.shared.name = txt
        }
        
        let joinId = self.meetingField.textField.stringValue.clearId()
        if joinId != "" {
            self.reLoadMeeting(joinId: joinId)
        }
    }
    
    
    @objc func historyBtnAction(senber:ZHButton)  {
        let relative = self.meetingField
        relative.layoutSubtreeIfNeeded()
        let controller = HistoryViewController()
        controller.delegate = self
        let autoheight = (PLISTSaveManager.readList().count+1)*26+10+10
        let height = autoheight > 100 ? 100:autoheight
        controller.kSize = CGSize.init(width: relative.frame.width+10, height: CGFloat(height))
        let lk =  Lk.create(controller: controller,current: .light)
        lk.show(relativeTo: CGPoint.init(x: 0, y: 0), of: relative, direccion: LDireccion.C2B)
    }
}

extension JoinViewController:NSTextFieldDelegate {
    
    func controlTextDidBeginEditing(_ obj: Notification) {
        let view = obj.object as? NSTextField
        let textField = view?.superview as? ZHTextField
        if textField == meetingField {
            self.tipLab.textColor = color_gray(160)
        }
    }
    func controlTextDidChange(_ obj: Notification) {
        let view = obj.object as? NSTextField
        let textField = view?.superview as? ZHTextField
        self.nameField.isBecomeFirst = textField == nameField
        self.meetingField.isBecomeFirst = !(textField == nameField)
    }
    
    func controlTextDidEndEditing(_ obj: Notification) {
        let view = obj.object as? NSTextField
        let textField = view?.superview as? ZHTextField
        if (textField != nil) {
            if textField!.style == .number {
                textField!.textField.stringValue = textField!.textField.stringValue
            }
        }
        self.nameField.isBecomeFirst = !(textField == nameField)
        self.meetingField.isBecomeFirst = textField == nameField
    }
    
    @objc func videoBtnAction(senber:NSButton) {
        let isok = senber.state==NSButton.StateValue.on ? true:false
        Td.sh().lc.isVdOpen = !isok
    }
    
    @objc func audioBtnAction(senber:NSButton) {
        let isok = senber.state==NSButton.StateValue.on ? true:false
        Td.sh().lc.isMute = isok
    }
    
}


extension JoinViewController {
    //获取进入会议数据
    func reLoadMeeting(joinId:String)  {
        let number = self.meetingField.textField.stringValue
        let name = self.nameField.textField.stringValue
        let pwd = self.option?.password
        let num = (self.option?.encryption != nil) ? (self.option?.roomid ?? ""):number
        
        guard var option = self.option,let ownid = UserInfoManager.shared.ownid else {
            return
        }
        option.number = num.clearId()
        option.roomid = num.clearId()
        option.name = name
        option.password = pwd
        option.ownid = ownid
        
        if number == Td.sh().params.userId {
            show_msg("会议号有误，您不能加入自己的会议号")
            return
        }
        
        self.joinBtn.isEnabled = false
        self.cacalBtn.isEnabled = false
        
        
        RtcEngine.responseHostData { (result) in
            OneEngine.shared.gojoinmeeting(roomid:  num.clearId(), userid: ownid) {
                TrtcEngine.close(classs: [JoinViewController.classForCoder(),MainViewController.classForCoder()])
            } enterFail: {
                self.joinBtn.isEnabled = true
                self.cacalBtn.isEnabled = true
            } resultPassword: {
                self.joinBtn.isEnabled = true
                self.cacalBtn.isEnabled = true
            }
        }
       
    }
}


extension JoinViewController {
    @objc func doMeetingNot(not:Notification) {
        guard let option = not.object as? OptionData else {
            return
        }
        self.option = option
        self.loadData()
    }
    
    @objc func loginStatus(notification:Notification) {
        if self.option?.isjoin == false{
            self.meetingField.textField.stringValue = self.option.roomid!.stringToPhone()
            self.nameField.textField.stringValue = self.option.name ?? ""
            show_msg("数据已刷新".localized())
        }
    }
}

extension JoinViewController:HistoryCtrlDelegate {
    func didSelect(controller: NSViewController, string data: String, row: Int) {
        let mode = Plist_historyMode.deserialize(from: data.toDict())
        if mode?.name == mt_history_clear {
            PLISTSaveManager.restList()
        }else {
            self.meetingField.textField.stringValue = mode?.roomId ?? ""
        }
    }
}
